package cz.fi.muni.pa165.hotelbookingmanagerdesktop;

import com.sun.jersey.api.client.ClientHandlerException;
import cz.fi.muni.pa165.hotelbookingmanagerapi.transferobjects.ContactTO;
import cz.fi.muni.pa165.hotelbookingmanagerapi.transferobjects.HotelTO;
import cz.fi.muni.pa165.hotelbookingmanagerdesktop.rest.HotelRESTManager;
import cz.fi.muni.pa165.hotelbookingmanagerdesktop.tablemodels.HotelTableModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Filip Bogyai
 */
public class HotelDialog extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;
    private boolean createHotel = true;
    private HotelRESTManager hotelRESTManager = new HotelRESTManager();
    private HotelTableModel hotelTableModel;
    private HotelTO hotel;
    private CountryPicker countryPicker = new CountryPicker();
    /**
     * Creates new form hotelDialog
     */
    public HotelDialog(HotelTableModel hotelTableModel) {
        initComponents(); 
        countryPicker.initializeComboBox(hotelCountryComboBox);
        setLocationRelativeTo(null);
        this.hotelTableModel=hotelTableModel;
        hotel= new HotelTO();
    }

    public HotelDialog(HotelTO hotel,HotelTableModel hotelTableModel){
        initComponents();
        countryPicker.initializeComboBox(hotelCountryComboBox);
        this.hotel=hotel;
        setLocationRelativeTo(null);
        this.hotelTableModel=hotelTableModel;

        hotelNameField.setText(hotel.getName());
        hotelAddressField.setText(hotel.getContact().getAddress());
        hotelCityField.setText(hotel.getContact().getCity());
        hotelCountryComboBox.setSelectedItem(hotel.getContact().getCountry());
        hotelTelephoneField.setText(hotel.getContact().getPhone());
        hotelEmailField.setText(hotel.getContact().getEmail());

        createHotel = false;
        hotelCreateButton.setText("Save");
        hotelDescriptionLabel.setText("Edit existing hotel");
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        hotelDescriptionLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        hotelNameField = new javax.swing.JTextField();
        hotelAddressField = new javax.swing.JTextField();
        hotelCityField = new javax.swing.JTextField();
        hotelTelephoneField = new javax.swing.JTextField();
        hotelEmailField = new javax.swing.JTextField();
        hotelCountryComboBox = new javax.swing.JComboBox();
        hotelCancelButton = new javax.swing.JButton();
        hotelCreateButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Hotel");

        hotelDescriptionLabel.setText("Create new hotel");

        jLabel2.setText("Name");

        jLabel3.setText("Contact Information :");

        jLabel4.setText("Address");

        jLabel5.setText("City");

        jLabel6.setText("Country");

        jLabel7.setText("Telephone");

        jLabel8.setText("Email");

        hotelNameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hotelNameFieldActionPerformed(evt);
            }
        });

        hotelCancelButton.setText("Cancel");
        hotelCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hotelCancelButtonActionPerformed(evt);
            }
        });

        hotelCreateButton.setText("Create");
        hotelCreateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hotelCreateButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(hotelCancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(hotelCreateButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(hotelDescriptionLabel)
                            .addComponent(jLabel3)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel8))
                                .addGap(69, 69, 69)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(hotelNameField)
                                    .addComponent(hotelAddressField)
                                    .addComponent(hotelCityField)
                                    .addComponent(hotelTelephoneField)
                                    .addComponent(hotelEmailField)
                                    .addComponent(hotelCountryComboBox, 0, 153, Short.MAX_VALUE))))
                        .addGap(0, 108, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(hotelDescriptionLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(hotelNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(hotelAddressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(hotelCityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(hotelCountryComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(hotelTelephoneField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(hotelEmailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hotelCancelButton)
                    .addComponent(hotelCreateButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void hotelNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hotelNameFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_hotelNameFieldActionPerformed

    private void hotelCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hotelCancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_hotelCancelButtonActionPerformed

    private void hotelCreateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hotelCreateButtonActionPerformed
      if (validateInformation()) {
            ContactTO contact = new ContactTO();
            contact.setAddress(hotelAddressField.getText());
            contact.setCity(hotelCityField.getText());
            contact.setCountry((String)hotelCountryComboBox.getSelectedItem());
            contact.setPhone(hotelTelephoneField.getText());
            contact.setEmail(hotelEmailField.getText());

            hotel.setName(hotelNameField.getText());
            hotel.setContact(contact);

            try {
                int status = createHotel ? hotelRESTManager.createHotel(hotel).getStatus() : hotelRESTManager.updateHotel(hotel).getStatus();
                switch(status) {
                    case 400:
                        JOptionPane.showMessageDialog(this, "An invalid hotel was sent to the server. Please check the information and try again.", "Error", JOptionPane.ERROR_MESSAGE);
                        break;
                    case 500:
                        JOptionPane.showMessageDialog(this, "An error occured on the server side. Please contact the administrator for more information.", "Error", JOptionPane.ERROR_MESSAGE);
                        break;
                    default:
                        hotelTableModel.setHotels(hotelRESTManager.findAllHotels());
                }
            } catch (ClientHandlerException che) {
                JOptionPane.showMessageDialog(this, "Server connection was lost. Please check your connection, or contact the administrator for further information. The application will now close.", "Cannot connect to server.", JOptionPane.ERROR_MESSAGE);
                System.exit(1);
            }
            dispose();
        }
    }//GEN-LAST:event_hotelCreateButtonActionPerformed

    private boolean validateInformation() {
        String errors = "";
        if (hotelNameField.getText().isEmpty()) {
            errors += "First name is a required field.\n";
        }
        if (hotelAddressField.getText().isEmpty()) {
            errors += "Address field is a required field.\n";
        }
        if (hotelCityField.getText().isEmpty()) {
            errors += "City field is a required field.\n";
        }
        if (hotelTelephoneField.getText().isEmpty()) {
            errors += "Telephone field is a required field.\n";
        } else if (!hotelTelephoneField.getText().matches("\\d+")) {
            errors += "Invalid telephone number.\n";
        }
        if (hotelEmailField.getText().isEmpty()) {
            errors += "Email field is a required field.\n";
        } else if (!hotelEmailField.getText().matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) {
            errors += "Invalid email address.\n";
        }
        if (errors.isEmpty()) {
            return true;
        } else {
            JOptionPane.showMessageDialog(this, errors, "Errors found", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField hotelAddressField;
    private javax.swing.JButton hotelCancelButton;
    private javax.swing.JTextField hotelCityField;
    private javax.swing.JComboBox hotelCountryComboBox;
    private javax.swing.JButton hotelCreateButton;
    private javax.swing.JLabel hotelDescriptionLabel;
    private javax.swing.JTextField hotelEmailField;
    private javax.swing.JTextField hotelNameField;
    private javax.swing.JTextField hotelTelephoneField;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    // End of variables declaration//GEN-END:variables
}
